package com.chenyue.cm.config.task;

import com.chenyue.cm.account.domain.JdAccount;
import com.chenyue.cm.account.service.JdAccountService;
import com.chenyue.cm.common.domain.JdCommonCron;
import com.chenyue.cm.common.service.JdCommonCronService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author libingxing
 */
@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    private final JdCommonCronService commonCronService;

    private final JdAccountService jdAccountService;

    public DynamicScheduleTask(JdCommonCronService commonCronService,JdAccountService jdAccountService) {
        this.commonCronService = commonCronService;
        this.jdAccountService = jdAccountService;
    }

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //2.1 从数据库获取执行周期
        List<JdCommonCron> cronList = commonCronService.lambdaQuery()
                .lt(JdCommonCron::getExcuteTime, LocalDateTime.now())
                .list();
        for (JdCommonCron commonCron : cronList) {
            final String cron = commonCron.getCron();
            taskRegistrar.addTriggerTask(
                    //1.添加任务内容(Runnable)
                    () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                    //2.设置执行周期(Trigger)
                    triggerContext -> {
                        //2.1 合法性校验.
                        if (StringUtils.isEmpty(cron)) {
//                            业务操作
                            jdAccountService.autoMaticAccount();
                        }
                        //2.3 返回执行周期(Date)
                        return new CronTrigger(cron).nextExecutionTime(triggerContext);
                    }
            );
        }
    }
}
